const http = require('./http')
const config = require('./config')
const host = config.host

// 当前时间戳
const now = () => {
  return Date.parse(new Date())
}

// 自定义日期
const dateFormat = (timestamp, type = 1) => {
  // 1=>1月1日，2=>周一，3=>1（月），4=>1（日）
  const date = new Date(parseInt(timestamp))
  let result = ''
  if (type === 1) {
    result = date.getMonth() + 1 + '月' + date.getDate() + '日'
  } else if (type === 2) {
    const arr2 = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    result = arr2[date.getDay()]
  } else if (type === 3) {
    result = date.getMonth() + 1
  } else if (type === 4) {
    result = date.getDate()
  } else if (type === 5) {
    result = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-' + date.getDate()
  }
  return result
}

// 格式化日期
const dtu = (str) => {
  const f = str.split(' ', 2)
  const d = (f[0] ? f[0] : '').split('-', 3)
  const t = (f[1] ? f[1] : '').split(':', 3)
  return (new Date(
    parseInt(d[0], 10) || null,
    (parseInt(d[1], 10) || 1) - 1,
    parseInt(d[2], 10) || null,
    parseInt(t[0], 10) || null,
    parseInt(t[1], 10) || null,
    parseInt(t[2], 10) || null
  )).getTime() / 1000
}

// 格式化时间戳
const utd = (_unixTime, _full) => {
  var date = new Date(_unixTime.toString().length == 10 ? parseInt( _unixTime + '000') : parseInt(_unixTime));
  var Y = date.getFullYear()
  var M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  if (_full) {
    return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
  } else {
    return Y + '-' + M + '-' + D
  }
}

// 取随机整数
const rand = (lower = 100, upper = 999) => {
  return Math.floor(Math.random() * (upper - lower)) + lower
}

// split
const split = (str = '', split = ',') => {
  return str.split(split)
}

// msg
const msg = (title = 'default msg') => {
  wx.showToast({ title: title, duration: 1500, icon: 'none' });
}

// alert
const alert = (content = '这是一个alert窗') => {
  return new Promise((resolve) => {
    wx.showModal({
      showCancel: false,
      content: content,
      success () {
        resolve()
      }
    })
  })
}

// confirm
const confirm = (content = '这是一个confirm窗') => {
  return new Promise((resolve) => {
    wx.showModal({
      content: content,
      success (res) {
        resolve(res)
      }
    })
  })
}

// getUserInfo
const getUserInfo = async (url = '') => {
  let result = null
  const codeRes = await wx.login()
  if (codeRes.code) {
    const res = await http.get(url, { code: codeRes.code })
    if (res.code == 0) {
      result = res.data
    }
    return result
  }
}

// pay
const pay = async (data, payUrl = '/weapp/pay') => {
  const res = await http.post(payUrl, data)
  return new Promise((resolve, reject) => {
    wx.requestPayment({
      timeStamp: res.data.timeStamp,
      nonceStr: res.data.nonceStr,
      package: res.data.package,
      signType: res.data.signType,
      paySign: res.data.paySign,
      success (res) { resolve(res) },
      complete () { reject() }
    })
  })
}

// scan
const scan = async () => {
  return new Promise((resolve, reject) => {
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        resolve(res.result)
      },
      fail: (res) => {
        // console.log(res)
      }
    })
  })
}

// chooseImage
const chooseImage = async (opts = { count: 1 }) => {
  return new Promise((resolve, reject) => {
    let data = {
      success: (res) => {
        resolve(res)
      },
      fail: (res) => {
        // console.log(res)
      }
    }
    Object.assign(data, opts)
    wx.chooseImage(data)
  })
}

// upload
const upload = async (data = { url: '', filePath: '', name: '', formData: {} }) => {
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: host + data.url,
      filePath: data.filePath,
      name: data.name,
      formData: data.formData,
      success: (res) => {
        const result = JSON.parse(res.data)
        resolve(result)
      }
    })
  })
}

module.exports = {
  now, dateFormat, dtu, utd, rand, split, msg, alert, confirm,
  getUserInfo, pay, scan, chooseImage, upload
}